package com.inibb.app.validator;

import com.inibb.app.exception.NumberExceedLimitException;
import com.inibb.app.util.lang.StringUtil;


public class IDValidateUtil {

	public static boolean isValidExternalUserID(String userID) {
		return isNonRepeatID(userID);

	}

	public static boolean isNonRepeatID(String id) {
		char[] chs = id.toCharArray();
		// RULE 01: Generate the ID excluding the combinations of 3 or more
		// consecutive identical digits (e.g. 111)
		for (char ch : chs) {
			char[] chq = new char[] { ch, ch, ch };
			if (id.contains(new String(chq))) {
				return false;
			}
		}
		// RULE 02: Generate the ID excluding the first 3 digits identical to
		// last 3 digits (e.g. 124124).
		for (int i = 0; i < chs.length - 2; i++) {
			char[] chq = new char[] { chs[i], chs[i + 1], chs[i + 2] };
			String subStr = new String(chq);
			int idx = id.indexOf(subStr);
			// to check if there is repeating string.
			if (id.indexOf(subStr, idx + 3) != -1) {
				return false;
			}
		}

		return true;
	}

	public static Long getNextValidID(int prefixDigit, Long cursor, int length) {
		// long cursor = Long.valueOf(super.generateID());
		String nbr = null;
		if (cursor >= 0L && cursor < Long.MAX_VALUE) {
			nbr = StringUtil
					.addLeadingZero(StringUtil.toString(cursor), length);
		} else {
			throw new NumberExceedLimitException(
					"Generated ID has been used up!");
		}

		// if prefixDigit less than or equal -1, then ignore prefix.
		if (prefixDigit > 0) {
			nbr = String.valueOf(prefixDigit) + nbr;
		}

		if (!IDValidateUtil.isNonRepeatID(nbr)) {
			cursor = getNextCursor(nbr, cursor);
			// log.debug(cursor+"|"+nbr);
			return getNextValidID(prefixDigit, cursor, length);
		}
		//System.out.println("return cursor :" + cursor);

		return cursor;
	}

	public static Long getNextValidID(int prefixDigit, Long cursor) {
		return getNextValidID(prefixDigit, cursor, 8);
	}

	public static Long getNextCursor(String strId, Long cursor) {
		//String ruid = org.apache.commons.lang.StringUtils.reverse(strId);

		int repeatCharIndex = getRepeatCharIndex(strId);
		//System.out.println("repeat index :" + repeatCharIndex);
		switch (repeatCharIndex) {
		case 10:
			cursor += 100000L;
			break;
		case 9:
			cursor += 10000L;
			break;
		case 8:
			cursor += 1000L;
			break;
		case 7:
			cursor += 100L;
			break;
		case 6:
			cursor += 10L;
			break;
		default:
			cursor++;
			break;
		}

		return cursor;
	}

	public static int getRepeatCharIndex(String userID) {

		int i = 0;
		char[] chs = userID.toCharArray();
		for (char ch : chs) {
			char[] chq = new char[] { ch, ch, ch };
			String s = new String(chq);
			if (userID.contains(s)) {
				int idx = userID.indexOf(s);
				
				i = 10 - idx;
				break;
			}
		}
		return i;
	}
}
